<template>
  <div class="category-container">
    <div class="category-header">
      <h2>内容分类管理</h2>
      <el-button type="primary" @click="showAddDialog(1)">添加一级分类</el-button>
    </div>
    <el-table
        :data="categoryTree"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="分类名称" width="200"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="240">
        <template slot-scope="{row}">
          <el-input-number v-model="row.sortOrder" @change="updateSortOrder(row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="{row}">
          <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="updateStatus(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="{row}">
          <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
          <el-button
              size="small"
              type="primary"
              @click="showAddDialog(2, row.id)"
              v-if="row.level === 1"
          >添加子分类
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="分类名称" required>
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input v-model="form.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="排序权重">
          <el-input-number v-model="form.sortOrder"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'categories',
  layout: "admin",
  data() {
    return {
      categoryTree: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        name: '',
        description: '',
        level: 1,
        parentId: null,
        sortOrder: 0,
        status: 1
      }
    }
  },
  methods: {
    loadCategories() {
      this.$axios.get('/api/categories')
          .then(response => {
            this.categoryTree = response.data;
          })
          // eslint-disable-next-line no-unused-vars
          .catch(error => {
            this.$message.error('加载分类失败');
          });
    },
    showAddDialog(level, parentId = null) {
      this.form = {
        name: '',
        description: '',
        level,
        parentId,
        sortOrder: 0,
        status: 1
      };
      this.dialogTitle = level === 1 ? '添加一级分类' : '添加子分类';
      this.dialogVisible = true;
    },
    showEditDialog(category) {
      this.form = {...category};
      this.dialogTitle = '编辑分类';
      this.dialogVisible = true;
    },
    submitForm() {
      if (!this.form.name) {
        this.$message.warning('请输入分类名称');
        return;
      }

      const request = this.form.id
          ? this.$axios.put(`/api/categories/${this.form.id}`, this.form)
          : this.$axios.post('/api/categories', this.form);

      request.then(() => {
        this.$message.success(this.form.id ? '更新成功' : '添加成功');
        this.dialogVisible = false;
        this.loadCategories();
      }).catch(error => {
        this.$message.error(error.response?.data?.error || '操作失败');
      });
    },
    handleDelete(category) {
      this.$confirm('确定要删除该分类吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/api/categories/${category.id}`)
            .then(() => {
              this.$message.success('删除成功');
              this.loadCategories();
            })
            .catch(error => {
              this.$message.error(error.response?.data?.error || '删除失败');
            });
      }).catch(() => {
      });
    },
    updateStatus(category) {
      this.$axios.put(`/api/categories/${category.id}`, {
        status: category.status
        // eslint-disable-next-line no-unused-vars
      }).catch(error => {
        this.$message.error('状态更新失败');
        this.loadCategories();
      });
    },
    updateSortOrder(category) {
      this.$axios.put(`/api/categories/${category.id}`, {
        sortOrder: category.sortOrder
        // eslint-disable-next-line no-unused-vars
      }).catch(error => {
        this.$message.error('排序更新失败');
        this.loadCategories();
      });
    }
  },
  mounted() {
    this.loadCategories();
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
